//
//  NetworkClient.swift
//  SwiftNetwork
//
//  Created by 万孟超 on 2022/1/11.
//

import UIKit
import Alamofire



class NetworkClient {
    
    static let shared = NetworkClient()

    var engineTask : [String : DataRequest] = [:]

    var completeTask : [String : Bool] = [:]

    var retryTask : [NetworkRetryModel] = []
    
    var timeOutRetryTask : [NetworkRetryModel] = []
    
    init() {
        NotificationCenter.default.addObserver(self, selector: #selector(startRetryNetwork), name: NSNotification.Name("NETWORK_RETRY"), object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(startTimeOutRetryNetwork), name: NSNotification.Name("NETWORK_TIMEOUT_RETRY"), object: nil)
    }
    
    @objc func startRetryNetwork() {
        for model in retryTask {
            model.networkRetry()
            print("网络切换后，自动发起重试")
        }
        retryTask.removeAll()
    }
    
    @objc func startTimeOutRetryNetwork() {
        for model in timeOutRetryTask {
            model.networkRetry()
            print("网络切换后，自动发起重试")
        }
        timeOutRetryTask.removeAll()
    }

    func addEngineTask(_ task : DataRequest, with enginePoint : String) {
        if !enginePoint.isEmpty {
            engineTask.updateValue(task, forKey: enginePoint)
            print("记录请求\(enginePoint)")
        }
    }

    func removeEngineTask(forEnginePoint enginePoint : String, isSuccess : Bool) {
        if !enginePoint.isEmpty && engineTask.keys.contains(enginePoint) {
            engineTask.removeValue(forKey: enginePoint)
            print("移除请求\(enginePoint)")
            completeTask.updateValue(isSuccess, forKey: enginePoint)
        }
    }
    
    func cancelNetwork(forEnginePoint enginePoint : String) {
        if !enginePoint.isEmpty && engineTask.keys.contains(enginePoint) {
            engineTask[enginePoint]?.cancel()
            print("取消请求\(enginePoint)")
        }
    }
    
    func addRetryNetwork(retryModel : NetworkRetryModel) {
        retryTask.append(retryModel)
        print("请求添加到重试列表")
    }
    
    func addTimeOutRetryNetwork(retryModel : NetworkRetryModel) {
        timeOutRetryTask.append(retryModel)
        autoStartTimeOutNetwork(retryModel)
        print("超时请求添加到重试列表")
    }
    
    func autoStartTimeOutNetwork(_ retryModel : NetworkRetryModel) {
        DispatchQueue.global().asyncAfter(deadline: .now() + 10) {
            if self.timeOutRetryTask.contains(retryModel) {
                retryModel.networkRetry()
                self.timeOutRetryTask.removeAll(where: {$0 === retryModel})
                print("超时请求自动重试")
            }
        }
    }
}
